package com.appkubes.fintech.admin.application.data.blacklist.controller;

import com.appkubes.common.utils.data.string.UUIDUtils;
import com.appkubes.fintech.admin.application.data.blacklist.entity.vo.BlackListAddVO;
import com.appkubes.fintech.admin.application.data.blacklist.entity.vo.BlackListSearchVO;
import com.appkubes.fintech.admin.application.data.blacklist.service.BlackListService;
import com.appkubes.fintech.common.response.Response;
import com.appkubes.fintech.core.po.FintechDataBlackList;
import com.appkubes.fintech.core.po.FintechDataBlackListExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;

/**
 * @Author: leeming
 * @Date: 2020-02-04 16:16
 * @Description:
 */
@Slf4j
@Api(tags = "黑名单相关")
@RestController
@RequestMapping("/data/blacklist")
public class BlackListController {

    @Resource
    BlackListService blackListService;

    @ApiOperation("获取当前黑名单列表")
    @PostMapping("/get")
    public Response<PageInfo<FintechDataBlackList>> get(@RequestBody @Valid BlackListSearchVO vo, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Response.fail("参数检查失败");
        }
        FintechDataBlackListExample example = new FintechDataBlackListExample();
        FintechDataBlackListExample.Criteria criteria = example.createCriteria();
        if (vo.getIdCardNum() != null && !vo.getIdCardNum().equals("")) {
            criteria.andIdCardNumEqualTo(vo.getIdCardNum());
        }
        if (vo.getPhone() != null && !vo.getPhone().equals("")) {
            criteria.andPhoneEqualTo(vo.getPhone());
        }
        if (vo.getRealName() != null && !vo.getRealName().equals("")) {
            criteria.andRealNameEqualTo(vo.getRealName());
        }
        PageHelper.startPage(vo.getPageVO().getPage(), vo.getPageVO().getPageSize());
        List<FintechDataBlackList> blackLists = blackListService.getBlackListDao().selectByExample(example);
        PageInfo pageInfo = new PageInfo(blackLists);

        return Response.success(pageInfo);
    }

    @ApiOperation("添加黑名单")
    @PostMapping("/add")
    public Response add(@RequestBody @Valid BlackListAddVO addVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Response.fail("参数检查失败");
        }

        if (addVO.getIdCardNum() == null && addVO.getPhone() == null && addVO.getRealName() == null)
            return Response.fail("姓名，电话，身份证号码不能全为空");

        if (addVO.getIdCardNum() != null || addVO.getPhone() != null) {
            FintechDataBlackListExample example = new FintechDataBlackListExample();
            if (addVO.getIdCardNum() != null)
                example.createCriteria().andIdCardNumEqualTo(addVO.getIdCardNum());
            if (addVO.getPhone() != null)
                example.createCriteria().andPhoneEqualTo(addVO.getPhone());
            List<FintechDataBlackList> lists = blackListService.getBlackListDao().selectByExample(example);
            if (lists != null && lists.size() > 0) {
                return Response.fail("已经存在");
            }
        }
        FintechDataBlackList blackList = new FintechDataBlackList();
        BeanUtils.copyProperties(addVO, blackList);
        blackList.setBlackListKey(UUIDUtils.getUUID());
        blackList.setCreateDate(new Date());
        int result = blackListService.getBlackListDao().insert(blackList);
        if (result == 1) {
            return Response.success();
        }
        return Response.fail();
    }


    @ApiOperation("批量增加黑名单")
    @PostMapping("/addByExcel")
    public Response addByExcel(@RequestParam("file") MultipartFile file){
        Integer sum = 0; ///总条数
        Integer success = 0;//成功数
        Workbook workbook = null;
        try {
            if(file!=null) {
                //获取excel文件
                workbook = Workbook.getWorkbook(file.getInputStream());
                Sheet sheet = workbook.getSheet(0);
                if (sheet.getRows()<1 || sheet.getRow(0).length<3)
                    return Response.fail("导入失败，数据表格式错误");

                int nameIndex=0,telIndex=1,idIndex=2;
                Cell[] cells = sheet.getRow(0);
                for (int i=0;i<cells.length;i++) {
                    if (cells[i].getContents().equals("姓名")) nameIndex = i;
                    if (cells[i].getContents().equals("手机号")) telIndex = i;
                    if (cells[i].getContents().equals("身份证")) idIndex = i;
                }

                sum = sheet.getRows() - 1;
                FintechDataBlackList blackList = null;
                for (int i=1;i<sheet.getRows();i++) {
                    cells = sheet.getRow(i);
                    String name = cells[nameIndex].getContents();
                    String tel = cells[telIndex].getContents();
                    String idcard = cells[idIndex].getContents();
                    if (name.equals("") && tel.equals("") && idcard.equals("")) {
                        continue;
                    }

                    blackList = new FintechDataBlackList();
                    blackList.setRealName(name);
                    blackList.setPhone(tel);
                    blackList.setIdCardNum(idcard);
                    blackList.setBlackListKey(UUIDUtils.getUUID());
                    blackList.setCreateDate(new Date());
                    try  {
                        int result = blackListService.getBlackListDao().insert(blackList);
                        success += result;
                    }
                    catch (Exception e) {
                    }
                }
            }
        } catch (Exception e) {
            log.error("黑名单excel导入异常："+e.getMessage());
            return Response.fail("导入异常，成功条数：" +success+",总条数："+sum);
        }finally{
            workbook.close();
        }
        return Response.success("导入成功，成功条数：" +success+",总条数："+sum);
    }

    @ApiOperation("删除黑名单")
    @PostMapping("/del")
    public Response del(String key) {
        int result = blackListService.getBlackListDao().deleteByPrimaryKey(key);
        if (result == 1) {
            return Response.success();
        }
        return Response.fail();
    }

    @ApiOperation("修改黑名单")
    @PostMapping("/update")
    public Response update(@RequestBody @Valid BlackListAddVO addVO, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Response.fail("参数检查失败");
        }
        FintechDataBlackList blackList = blackListService.getBlackListDao().selectByPrimaryKey(addVO.getBlackListKey());
        if (blackList == null) {
            return Response.fail("记录不存在");
        }
        BeanUtils.copyProperties(addVO, blackList);
        int result = blackListService.getBlackListDao().updateByPrimaryKey(blackList);
        if (result == 1) {
            return Response.success();
        }
        return Response.fail();
    }
}
